name: foodgram_workflow

on:
  push:
    branches: [ master ]
  pull_request:
    branches: [ master ]

jobs:
  tests:
    runs-on: ubuntu-latest

    steps:
      # для клонирования репозитория применён предустановленный action
    - uses: actions/checkout@v2
    - name: Set up Python
      # для установки Python-окружения
      uses: actions/setup-python@v2
      with:
        python-version: 3.8

    - name: Install dependencies
      run: |
        # обновление pip
        python -m pip install --upgrade pip
        # установка flake8 и его плагинов
        pip install flake8 pep8-naming flake8-broken-line flake8-return flake8-isort
        # установка зависимостей
        pip install -r backend/requirements.txt

    - name: Test with flake8 and django tests
      run: |
        # запуск проверки проекта по flake8
        python -m flake8

  build_and_push_to_docker_hub:
    if: github.ref == 'refs/heads/master' || github.ref == 'refs/heads/main'
    name: Push Docker image to Docker Hub
    runs-on: ubuntu-latest
    needs: tests
    steps:
      - name: Check out the repo
        uses: actions/checkout@v2 # Проверяет доступность репозитория DockerHub для workflow
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v1 # Вызывает сборщик контейнеров docker
      - name: Login to Docker
        uses: docker/login-action@v1 # Запуск скрипта авторизации на DockerHub
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}
      - name: Push to Docker Hub
        uses: docker/build-push-action@v2 # Выполняет push образа в DockerHub
        with:
          context: ./backend
          push: true
          tags: ${{ secrets.DOCKER_USERNAME }}/foodgram:v1 # <логин-на-docker-hub>/<репозиторий-на-docker-hub>:latest
      - name: Push frontend to Docker Hub
        uses: docker/build-push-action@v2
        with:
          context: ./frontend
          push: true
          tags: ${{ secrets.DOCKER_USERNAME }}/foodgram_frontend:v1

  deploy:
    if: github.ref == 'refs/heads/master' || github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    needs: build_and_push_to_docker_hub
    steps:
      - name: executing remote ssh commands to deploy
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.HOST }}
          username: ${{ secrets.USER }}
          key: ${{ secrets.SSH_KEY }}
          passphrase: ${{ secrets.PASSPHRASE }} # Если ваш ssh-ключ защищён фразой-паролем
          script: |
            sudo docker pull ebudaev/foodgram_frontend:v1
            sudo docker pull ebudaev/foodgram:v1
            sudo docker-compose stop
            sudo docker-compose rm -f backend --build
            rm .env
            touch .env
            echo DB_ENGINE=${{ secrets.DB_ENGINE }} >> .env
            echo DB_NAME=${{ secrets.DB_NAME }} >> .env
            echo POSTGRES_USER=${{ secrets.POSTGRES_USER }} >> .env
            echo POSTGRES_PASSWORD=${{ secrets.POSTGRES_PASSWORD }} >> .env
            echo DB_HOST=${{ secrets.DB_HOST }} >> .env
            echo DB_PORT=${{ secrets.DB_PORT }} >> .env
            echo SECRET_KEY=${{ secrets.SECRET_KEY }} >> .env
            echo DEBUG=${{ secrets.DEBUG }} >> .env
            echo ALLOWED_HOSTS=${{ secrets.ALLOWED_HOSTS }} >> .env
            sudo docker-compose up -d
            sudo docker-compose exec -T backend python manage.py collectstatic --noinput
            sudo docker-compose exec -T backend python manage.py makemigrations --noinput
            sudo docker-compose exec -T backend python manage.py migrate --noinput

  send_message:
    if: github.ref == 'refs/heads/master'
    runs-on: ubuntu-latest
    needs: deploy
    steps:
      - name: send message
        uses: appleboy/telegram-action@master
        with:
          to: ${{ secrets.TELEGRAM_TO }}
          token: ${{ secrets.TELEGRAM_TOKEN }}
          message: ${{ github.workflow }} успешно выполнен!
